package com.fresh.controller;

import com.fresh.common.ResponseResult;
import com.github.pagehelper.PageInfo;
import com.fresh.entity.Pay;
import com.fresh.entity.PayQO;
import com.fresh.service.YingFuKuanService;
import com.fresh.util.SnowflakeIdWorker;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/yingfukuan")
public class YingFuKuanController {
    @Autowired
    SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    YingFuKuanService yingFuKuanService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping({"/list/{pageNum}"})
    public Object list(PayQO payQO, @PathVariable(required = false) Integer pageNum) {
        if (pageNum == null) {
            pageNum = 1;
        }
        PageInfo<Pay> pageInfo = yingFuKuanService.findPageInfoByCondition(payQO, pageNum, 4);
        return new ResponseResult(200, "success", pageInfo);

    }

    @PostMapping("/add")
    public Object add(@RequestBody Pay pay) {
        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String data = sdf.format(dt);

        pay.setPayId(snowflakeIdWorker.nextId());
        pay.setPayTotal(pay.getRiPrice().multiply(new BigDecimal(pay.getRiNum())));
        pay.setPayIn(data);
        yingFuKuanService.add(pay);
        return new ResponseResult(200, "success", null);
    }

    @PostMapping("/pay")
    public Object pay(@RequestBody Pay pay) {
        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String data = sdf.format(dt);

        pay.setPayEnd(data);

        rabbitTemplate.convertAndSend("exchangeOrder", "order", pay);

/*        rabbitTemplate.convertAndSend("exchangeDelay", "delay", pay, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //设置消息延迟发送的时间
                message.getMessageProperties().setDelay(10 * 1000);
                return message;
            }
        });*/

        return pay;
    }

}
